<?php

class Application_Model_ListaMapper
{
	protected $_dbTable;
	
		
	public function setDbTable($dbTable, $tableName)
    {
        if (is_string($dbTable)) {
        	//Creamos la instancia
            $dbTable = new $dbTable();
            $dbTable->queTabla($tableName);
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided Lista');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }
 
    public function getDbTable($tableName)
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Lista', $tableName);
        }
        return $this->_dbTable;
    }
    
	public function fetchAll($tableName)
	{
		$resultSet = $this->getDbTable($tableName)->fetchAll(null, 'descripcion DESC');
		
		$entries = array();
				
		foreach ($resultSet as $row) {
			$lista = new Application_Model_Lista();

			
			$lista->setId($row->id)
					  ->setDescripcion($row->descripcion);
					  
			$entries[] = $lista;
		}
		return $entries;
	}
	
	public function find($id, Application_Model_Lista $lista, $tableName)
    {
        $result = $this->getDbTable($tableName)->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $lista->setId($row->id)
                ->setDescripcion($row->descripcion);
    }
    
	public function save(Application_Model_Lista $lista, $tableName)
    {
        $data = array('id'  	    => $lista->getId(),
            		  'descripcion' => $lista->getDescripcion()
        );
                
        if (null === ($id = $lista->getId())) {        	
            unset($data['id']);
            $this->getDbTable($tableName)->insert($data);            
        } else {
            $this->getDbTable($tableName)->update($data, array('id = ?' => $id));
        }
    }
    
    public function delete($tableName, $id)
    {
    	try {
    		$this->getDbTable($tableName)->delete("id = $id");
    		return 0;
    	} catch (Exception $e) {
    		return $e->getCode();
    	}    	
    	
    }
	
}

